﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;

namespace XML文件的保存与打开
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Save_Click(object sender, EventArgs e)
        {
            XmlDocument xDoc = new XmlDocument();
            XmlDeclaration declaration = xDoc.CreateXmlDeclaration("1.0", "utf-8", "yes");
            xDoc.AppendChild(declaration);
            XmlElement elem = xDoc.CreateElement("Cabinets");
            xDoc.AppendChild(elem);
            XmlElement cabinet = xDoc.CreateElement("Cabinet");
            elem.AppendChild(cabinet);

            cabinet.SetAttribute("编号", "1");
            XmlElement name = xDoc.CreateElement("Name");
            cabinet.AppendChild(name);
            name.SetAttribute("名称","测试案例");
            name.InnerText = "在这里写入文字说明";
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            string foldPath = "";
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                foldPath = dialog.SelectedPath + @"\" + @"\Demo.xml";

                xDoc.Save(foldPath);
                MessageBox.Show(" 生成Demo文件成功!", "提示");
            }
            else
            {
                MessageBox.Show(" 请选择文件生成路径!", "提示");
            }
        }

        private void Open_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            dlg.Title = "请选择要打开的文件";
            dlg.Filter = "xml files (*.xml)|*.xml";
            dlg.FilterIndex = 1;
            dlg.RestoreDirectory = false;
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                XmlReader xmlReader = new XmlTextReader(dlg.FileName);
                XmlDocument xml = new XmlDocument();
                xml.Load(xmlReader);
                //获取根节点  Cabinets
                XmlNode node = xml.SelectSingleNode("Cabinets");
                //编号集合
                XmlNodeList list = node.ChildNodes;
                //通过对该list进行操作 完成程序功能
            }
        }
    }
}
